package com.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/27 14:03
 * @Description: 日志切面
 */
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(public * com.demo.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //记录请求内容
        String URL = request.getRequestURL().toString();
        String HTTP_METHOD = request.getMethod();
        String IP = request.getRemoteAddr();
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        String name = joinPoint.getSignature().getName();
        String CLASS_METHOD = declaringTypeName + "." + name;
        String ARGS = Arrays.toString(joinPoint.getArgs());

        System.out.println("URL:" + URL);
        System.out.println("HTTP_METHOD:" + HTTP_METHOD);
        System.out.println("IP:" + IP);
        System.out.println("CLASS_METHOD:" + CLASS_METHOD);
        System.out.println("ARGS:" + ARGS);

    }


    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        System.out.println("方法的返回值 : " + ret);
    }

    //后置异常通知
    @AfterThrowing("webLog()")
    public void throwss(JoinPoint joinPoint) {
        System.out.println("方法异常时执行.....");
    }

    //后置最终通知--final增强，不管是抛出异常或者正常退出都会执行
    @After("webLog()")
    public void after(JoinPoint jp) {
        System.out.println("方法最后执行.....");
    }


    //环绕通知--环绕增强，相当于MethodInterceptor
//    @Around("webLog()")
//    public Object arround(ProceedingJoinPoint pjp) {
//        System.out.println("方法环绕start.....");
//        try {
//            Object o =  pjp.proceed();
//            System.out.println("方法环绕proceed，结果是 :" + o);
//            return o;
//        } catch (Throwable e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
}
